# coding=utf-8
"""
统计出每个用户红包使用情况，记录到mongodb
"""
import os
import sys
import datetime
import json

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")

from common.coupon.model import AccountCoupon, COUPON_STATUS
from common import orm
from sqlalchemy import func
from common.stats import MG_BIGBANG_COLL

coupons = orm.session.query(AccountCoupon.user_id, AccountCoupon.status, func.sum(AccountCoupon.price)) \
    .group_by(AccountCoupon.user_id).group_by(AccountCoupon.status).all()

data = {}  # key: user_id
for user_id, coupon_status, price in coupons:
    data.setdefault(user_id, {'create': 0, 'use': 0, 'expire': 0})
    data[user_id]['create'] += int(price)
    if coupon_status == COUPON_STATUS.USED:
        data[user_id]['use'] += int(price)
    if coupon_status == COUPON_STATUS.EXPIRED:
        data[user_id]['expire'] += int(price)

    print user_id

    MG_BIGBANG_COLL.user_stats.update(
        {"_id": user_id},
        {"$set":
             {"coupon.create": data[user_id]['create'],
              "coupon.use": data[user_id]['use'],
              "coupon.expire": data[user_id]['expire']
              }}
    )
